export default {
  namespaced: true,
  state: () => ({
    cart: JSON.parse(uni.getStorageSync('uni-cart') || '[]'),
  }),
  mutations: {
    addToCart(state, goods) {
      const findGoods = state.cart.find(item => item.goods_id === goods.goods_id)
      if (!findGoods) {
        state.cart.push(goods)
      } else {
        findGoods.goods_count++
      }
      this.commit('m_cart/saveToStorage')
    },
    saveToStorage(state) {
      uni.setStorageSync('uni-cart', JSON.stringify(state.cart))
    },
    changeCheckedStatus(state, goods) {
      const findGoods = state.cart.find(item => item.goods_id === goods.goods_id)
      findGoods.goods_state = goods.goods_state
      this.commit('m_cart/saveToStorage')
    },
    deleteGoods(state, goods) {
      state.cart = state.cart.filter(item => item.goods_id !== goods.goods_id)
      this.commit('m_cart/saveToStorage')
    },
    updateAllchecked(state,checked){
      state.cart.forEach(item => item.goods_state = checked)
    }
  },
  getters: {
    total(state) {
      let c = 0
      state.cart.forEach(item => c += item.goods_count)
      return c
    },
    checkCount(state) {
      return state.cart.filter(item => item.goods_state).reduce((total, item) => total += item.goods_count, 0)
    },
    totalPrice(state){
      return state.cart.filter(item => item.goods_state).reduce((total, item) => total += item.goods_count*item.goods_price, 0).toFixed(2)
    }
  }
}